<template>
  <div class="app-container">
    <div class="pageContent bgFF">
      <div class="goodInfoBox">
        <el-descriptions title="商品信息" direction="vertical" border>
          <el-descriptions-item :rowspan="2" :width="200" label="图片" align="center">
            <el-image
                style="width: 60px; height: 60px;"
                :src="setCoverUrl(goodData.cover)"
            />
          </el-descriptions-item>
          <el-descriptions-item label="名称" :width="200">
            <el-text style="width: 100%;" line-clamp="1">{{ goodData.name }}</el-text>
          </el-descriptions-item>
          <el-descriptions-item label="编码" :width="200">
            <el-text style="width: 100%;" line-clamp="1">{{ goodData.goodsNo }}</el-text>
          </el-descriptions-item>
          <el-descriptions-item label="条码" :width="200">
            <el-text style="width: 100%;" line-clamp="1">{{ goodData.barCode }}</el-text>
          </el-descriptions-item>
          <el-descriptions-item label="库存" :width="200">
            <el-text style="width: 100%;" line-clamp="1">{{ goodData.stock }}</el-text>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <div class="pageContentTop pageFlex pageSpaceBetween">
        <div class="itemBox" :class="{'active': step >= 1}" @click="handleStep(1)">
          填写采购信息
          <div class="sanBox"></div>
        </div>
        <div class="itemBox" :class="{'active': step >= 2}" @click="handleStep(2)">
          填写入库信息
          <div class="whiteSanBox"></div>
          <div class="sanBox"></div>
        </div>
        <div class="itemBox" :class="{'active': step >= 3}" @click="handleStep(3)">
          完成入库
          <div class="whiteSanBox"></div>
        </div>
      </div>
      <el-form class="formBox" ref="formRef" :model="form" :rules="rules" label-width="200">
        <div class="normalBox" v-if="step === 1">
          <div class="titleBox pageFlex pageAlignCenter">
            <div class="line"></div>
            <div class="title">采购信息</div>
          </div>
          <div class="contentBox bgFF">
            <el-form-item label="采购人" prop="purchaseName">
              <div class="valueBox pageFlex pageAlignCenter" @click="showTableModal('purchaseName')">
                <el-text class="value">{{ form.purchaseName || '请选择采购人' }}</el-text>
                <el-icon><ArrowRight /></el-icon>
              </div>
            </el-form-item>
            <el-form-item label="采购成本价格" prop="costPrice">
              <el-input
                  class="inputBox"
                  v-model="form.costPrice"
                  placeholder="请输入采购成本价格"
                  clearable
                  type="number"
              />
            </el-form-item>
            <el-form-item label="市场参考价" prop="price">
              <el-input
                  class="inputBox"
                  v-model="form.price"
                  placeholder="请输入市场参考价"
                  clearable
                  type="number"
              />
            </el-form-item>
            <el-form-item label="采购数量" prop="purchaseNumber">
              <el-input-number class="inputBox" :min="1" v-model="form.purchaseNumber"/>
            </el-form-item>
            <el-form-item label="采购说明" prop="purchaseRemarks">
              <el-input
                  class="textareaBox"
                  v-model="form.purchaseRemarks"
                  type="textarea"
                  :rows="6"
                  placeholder="请输入采购说明"
              />
            </el-form-item>
            <el-form-item prop="purchaseVoucherNo">
              <template #label="e">
                <div class="pageFlex pageAlignCenter">
                  <el-text>采购凭证编号</el-text>
                  <el-tooltip
                    class="box-item"
                    effect="dark"
                    content="采购凭证编号即采购单单号"
                    placement="bottom"
                  >
                    <el-icon style="color: var(--el-color-primary);cursor: pointer;"><QuestionFilled /></el-icon>
                  </el-tooltip>
                </div>
              </template>
              <el-input
                  class="inputBox"
                  v-model="form.purchaseVoucherNo"
                  placeholder="请输入采购凭证编号"
                  clearable
              />
            </el-form-item>
            <el-form-item label="采购凭证" prop="purchaseVoucher">
              <template #label="e">
                <div class="pageFlex pageAlignCenter">
                  <el-text>采购凭证</el-text>
                  <el-tooltip
                    class="box-item"
                    effect="dark"
                    content="采购凭证即上传采购单的图片"
                    placement="bottom"
                  >
                    <el-icon style="color: var(--el-color-primary);cursor: pointer;"><QuestionFilled /></el-icon>
                  </el-tooltip>
                </div>
              </template>
              <div class="imgBox">
                <ImageUpload v-model="form.purchaseVoucher" bg="#FFFFFF"></ImageUpload>
              </div>
            </el-form-item>
          </div>
          <div class="line"></div>
          <div class="dataManageBottom pageFlex pageFlexCenter">
            <el-button type="primary" @click="handleStep()">下一步</el-button>
          </div>
        </div>
        <div class="normalBox" v-if="step === 2">
          <div class="titleBox pageFlex pageAlignCenter">
            <div class="line"></div>
            <div class="title">入库信息</div>
          </div>
          <div class="contentBox bgFF">
            <el-form-item prop="entryVoucherNo">
              <template #label="e">
                <div class="pageFlex pageAlignCenter">
                  <el-text>入库凭证编号</el-text>
                  <el-tooltip
                    class="box-item"
                    effect="dark"
                    content="入库凭证编号即入库单单号"
                    placement="bottom"
                  >
                    <el-icon style="color: var(--el-color-primary);cursor: pointer;"><QuestionFilled /></el-icon>
                  </el-tooltip>
                </div>
              </template>
              <el-input
                class="inputBox"
                v-model="form.entryVoucherNo"
                placeholder="请输入入库凭证编号"
                clearable
              />
            </el-form-item>
            <el-form-item label="入库凭证" prop="entryVoucher">
              <template #label="e">
                <div class="pageFlex pageAlignCenter">
                  <el-text>入库凭证</el-text>
                  <el-tooltip
                    class="box-item"
                    effect="dark"
                    content="入库凭证即入库单的图片"
                    placement="bottom"
                  >
                    <el-icon style="color: var(--el-color-primary);cursor: pointer;"><QuestionFilled /></el-icon>
                  </el-tooltip>
                </div>
              </template>
              <div class="imgBox">
                <ImageUpload v-model="form.entryVoucher" bg="#FFFFFF"></ImageUpload>
              </div>
            </el-form-item>
            <el-form-item label="入库数量" prop="number">
              <el-input-number class="inputBox" :min="1" v-model="form.number"/>
            </el-form-item>
            <el-form-item label="入库说明" prop="notes">
              <el-input
                  class="textareaBox"
                  v-model="form.notes"
                  type="textarea"
                  :rows="6"
                  placeholder="请输入入库说明"
              />
            </el-form-item>
          </div>
          <div class="line"></div>
          <div class="dataManageBottom pageFlex pageFlexCenter">
            <el-button type="primary" @click="handleStep(1)">上一步</el-button>
            <el-button type="primary" @click="handleStep()">下一步</el-button>
          </div>
        </div>
        <div class="normalBox" v-if="step === 3">
          <div class="titleBox pageFlex pageAlignCenter">
            <div class="line"></div>
            <div class="title">确认信息并入库</div>
          </div>
          <div class="contentBox bgFF">
            <el-result
                icon="success"
                title="提示"
                sub-title="请确认前面步骤的内容都填写完毕且信息无误后，点击下方提交按钮即可入库"
            >
              <template #extra>
                <div class="dataManageBottom pageFlex pageFlexCenter">
                  <el-button type="primary" @click="handleStep(2)">上一步</el-button>
                  <el-button type="primary" :loading="submitLoading" @click="submitNow">提交</el-button>
                </div>
              </template>
            </el-result>
          </div>
        </div>
      </el-form>
    </div>
    <el-dialog v-model="purchaseShow" :title="purchaseTitle" width="728">
      <div class="tableModalBox" v-if="purchaseShow">
        <div class="tableModalBox_top pageFlex pageAlignCenter">
          <div class="line"></div>
          <div class="title">请进行选择</div>
        </div>
        <div class="searchBox">
          <el-form :model="purchaseParams" ref="purchaseTableModal" :inline="true" @submit.prevent>
            <el-form-item prop="name" style="margin: 0 6px 0 0;">
              <el-input
                  class="inputBox"
                  v-model="purchaseParams.name"
                  placeholder="请输入用户名查询"
                  clearable
                  @keyup.enter="handleTableModalQuery()"
              />
            </el-form-item>
            <el-form-item style="margin: 0 6px 0 0;">
              <el-button class="normalFormBg searchBtn" icon="Search" @click="handleTableModalQuery()"></el-button>
              <el-button class="normalFormBg searchBtn" icon="Refresh" @click="resetTableModalQuery()"></el-button>
            </el-form-item>
          </el-form>
        </div>
        <div class="tableBox">
          <el-table
            ref="purchaseTableRef"
            v-loading="purchaseLoading"
            :data="purchaseDataList"
            border
            height="400"
            @select="handleTableModalSelect"
            @select-all="handleTableModalAll">
            <el-table-column type="selection" width="55" />
            <el-table-column prop="userId" label="用户ID" width="150" :show-overflow-tooltip="true" fixed="left"></el-table-column>
            <el-table-column prop="userName" label="用户名" width="200" :show-overflow-tooltip="true"></el-table-column>
            <el-table-column prop="nickName" label="用户昵称" width="200" :show-overflow-tooltip="true"></el-table-column>
            <el-table-column prop="phonenumber" label="手机号" width="120" :show-overflow-tooltip="true"></el-table-column>
            <template #empty>
              <el-empty description="暂无数据" />
            </template>
          </el-table>
          <div class="pageFlex pageAlignCenter pageSpaceBetween" style="margin-top: 20px;">
            <div class="totalText">共计 {{purchaseTotal}} 条</div>
            <el-pagination background layout="prev, pager, next" :total="purchaseTotal" :current-page="purchaseParams.pageNum" :page-size="purchaseParams.pageSize" @current-change="handleTablePageChange"/>
          </div>
        </div>
        <div class="lineBox"></div>
        <div class="bottomBox pageFlex pageFlexCenter">
          <el-button @click="clearTableModalChoose">清空当前选择</el-button>
          <el-button type="primary" :disabled="!purchaseCur" @click="confirmTableModalChoose">确认选择</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script setup>
import ImageUpload from '@/views/gasManage/components/ImageUpload';
import {computed, nextTick, onMounted} from "vue";
import { listUser } from "@/api/system/user";
const { proxy } = getCurrentInstance();
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const goodData = ref({
  id: '',
  cover: '',
  goodsNo: '',
  stock: ''
})
const setCoverUrl = computed(()=>{
  return url => {
    if(url){
      return baseUrl+url
    }
    return  ''
  }
})
// -----------------------------------设置步骤---------------------------------
let step = ref(1);
function handleStep(num){
  if(num < step.value){
    stepChange(num);
  }else{
    proxy.$refs["formRef"].validate(valid => {
      if (valid) {
        stepChange(num);
      }else{
        proxy.$modal.msgError('填写内容有误！请检查');
      }
    })
  }
}
function stepChange(num){
  if(num){
    step.value = num;
  }else{
    step.value++;
  }
}
// -----------------------------------表单--------------------------------------
const form = ref({
  purchaseId: '',
  purchaseMobile: '',
  purchaseName: '',
  purchaseNumber: 1,
  purchaseRemarks: '',
  purchaseVoucher: '',
  purchaseVoucherNo: '',
  costPrice: '',
  price: '',
  entryVoucher: '',
  entryVoucherNo: '',
  number: 1,
  operationType: 0,
  notes: ''
})
const checkCostPrice = (rule, value, callback) => {
  if(form.value.price !== '' && Number(form.value.price) < Number(value)){
    callback(new Error('商品成本价格不能大于商品价格！'));
  }else{
    callback();
  }
}
const checkPrice = (rule, value, callback) => {
  if(form.value.costPrice !== '' && Number(value) < Number(form.value.costPrice)){
    callback(new Error('商品价格不能小于商品成本价格！'));
  }else{
    callback();
  }
}
const checkPurchaseVoucherNo = (rule, value, callback) => {
  if(value === '' && form.value.purchaseVoucher !== ''){
    callback(new Error('请输入采购凭证编号！'));
  }else{
    callback();
  }
}
const checkPurchaseVoucher = (rule, value, callback) => {
  if(value === '' && form.value.purchaseVoucherNo !== ''){
    callback(new Error('请上传采购凭证！'));
  }else{
    callback();
  }
}
const rules = ref({
  purchaseName: [{ required: true, message: "请选择采购人！", trigger: "blur" }],
  purchaseNumber: [
    { required: true, message: "采购数量不能为空", trigger: "blur" }
  ],
  costPrice: [
    { required: true, message: "成本价格不能为空", trigger: "blur" },
    {validator: checkCostPrice, trigger: 'blur'}
  ],
  price: [
    { required: true, message: "价格不能为空", trigger: "blur" },
    {validator: checkPrice, trigger: 'blur'}
  ],
  entryVoucher: [{ required: true, message: "请上传入库凭证", trigger: "blur" }],
  entryVoucherNo: [{ required: true, message: "入库凭证编号不能为空", trigger: "blur" }],
  number: [{ required: true, message: "入库数量不能为空", trigger: "blur" }],
  purchaseVoucher: [{ validator: checkPurchaseVoucher, trigger: 'blur'}],
  purchaseVoucherNo: [{ validator: checkPurchaseVoucherNo, trigger: 'blur'}]
})
// --------------------------------------入库------------------------------------------
import {CircleCheck} from "@element-plus/icons-vue";
import { addInventoryRecordApi } from '@/api/gasManage/stockManage/inventoryHistory';
const submitLoading = ref(false);
function submitNow(){
  if(submitLoading.value) return;
  proxy.$refs["formRef"].validate(valid=>{
    if(valid){
      submitLoading.value = true;
      let params = JSON.parse(JSON.stringify(form.value));
      params.price = Number(params.price);
      params.costPrice = Number(params.costPrice);
      params.purchaseId = Number(params.purchaseId);
      params.goodsId = Number(goodData.value.id);
      params.warehouseId = goodData.value.warehouseId;
      params.shelfId = goodData.value.shelfId;
      params.locationId = goodData.value.locationId;
      addInventoryRecordApi([params]).then(() => {
        submitLoading.value = false;
        ElMessageBox.confirm(
            '商品入库成功',
            '提示',
            {
              type: 'success',
              icon: markRaw(CircleCheck),
              showCancelButton: false
            }
        ).then(()=>{
          toBack();
        })
      }).catch(()=>{
        submitLoading.value = false;
      })
    }else{
      proxy.$modal.alertWarning('填写内容有误！请检查');
      submitLoading.value = false;
    }
  })
}
// -----------------------------------表格弹窗通用--------------------------------------
function showTableModal(name){
  purchaseShow.value = false;
  purchaseCur.value = null;
  if(name === 'purchaseName'){
    purchaseShow.value = true;
    purchaseTitle.value = '选择采购人';
    handleTableModalQuery();
    nextTick(()=>{
      proxy.$refs.purchaseTableRef.clearSelection();
    })
  }
}
function handleTableModalQuery(){
  if(purchaseShow.value){
    purchaseParams.value.pageNum = 1;
  }
  handleGetTableList();
}
function handleGetTableList(){
  if(purchaseShow.value){
    purchaseLoading.value = true;
    listUser(purchaseParams.value).then(res=>{
      purchaseTotal.value = Number(res.total);
      purchaseDataList.value = Array.isArray(res.rows) ? res.rows : [];
      purchaseLoading.value = false;
      if(form.value.purchaseId && purchaseDataList.value.length){
        let index = purchaseDataList.value.findIndex(item=>item.userId === form.value.purchaseId);
        if(index !== -1){
          nextTick(()=>{
            purchaseCur.value = purchaseDataList.value[index];
            proxy.$refs.purchaseTableRef.toggleRowSelection(purchaseCur.value, true);
          })
        }
      }
    }).catch(()=>{
      purchaseLoading.value = false;
      purchaseDataList.value = [];
    })
  }
}
function resetTableModalQuery(){
  if(purchaseShow.value){
    proxy.resetForm("purchaseTableModal");
    handleTableModalQuery();
  }
}
function handleTableModalSelect(e){
  let data = e[0];
  if(purchaseShow.value){
    if(e.length > 1){
      data = e[1]
    }
    if(!data || (purchaseCur.value && purchaseCur.value.userId && purchaseCur.value.userId === data.userId)){
      purchaseCur.value = null;
      return false;
    }
    let index = purchaseDataList.value.findIndex(item=>item.userId === data.userId);
    proxy.$refs.purchaseTableRef.clearSelection();
    purchaseCur.value = data;
    proxy.$refs.purchaseTableRef.toggleRowSelection(purchaseDataList.value[index], true);
  }
}
function handleTableModalAll(){
  if(purchaseShow.value){
    proxy.$refs.purchaseTableRef.clearSelection();
    purchaseCur.value = null;
  }
}
function handleTablePageChange(e){
  if(purchaseShow.value){
    purchaseParams.value.pageNum = e;
    handleGetTableList();
  }
}
function clearTableModalChoose(){
  if(purchaseShow.value){
    form.value.purchaseId = '';
    form.value.purchaseMobile = '';
    form.value.purchaseName = '';
    proxy.$refs.purchaseTableRef.clearSelection();
    hideTableModal();
  }
}
function confirmTableModalChoose(){
  if(purchaseShow.value){
    form.value.purchaseId = purchaseCur.value.userId;
    form.value.purchaseMobile = purchaseCur.value.phonenumber;
    form.value.purchaseName = purchaseCur.value.userName;
    hideTableModal();
  }
}
function hideTableModal(){
  if(purchaseShow.value){
    purchaseShow.value = false;
  }
}
// -----------------------------------选择采购人--------------------------------------
const purchaseShow = ref(false);
const purchaseLoading = ref(false);
const purchaseDataList = ref([]);
const purchaseTotal = ref(0);
const purchaseCur = ref(null);
const purchaseTitle = ref('');
const purchaseParams = ref({
  pageNum: 1,
  pageSize: 10,
  userName: ''
});
// -----------------------------------初始化------------------------------------
import { useRoute } from "vue-router";
import { searchGoodByIdApi } from '@/api/gasManage/stockManage/goodInfo';
import {ElLoading, ElMessageBox} from "element-plus";
const route = useRoute();
onMounted(()=>{
  goodData.value.id = route.params.id;
  initData();
})
function initData(){
  const loading = ElLoading.service({
    lock: true,
    text: '加载中~',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  searchGoodByIdApi(goodData.value.id).then(res => {
    goodData.value = res.data;
    loading.close();
    if(!goodData.value.cover){
      ElMessageBox.confirm(
        '检测到您的商品数据未填写完整，请先完成商品信息修改！',
        '提示',
        {
          type: 'danger',
          showCancelButton: false
        }
      ).then(()=>{
        toBack();
      })
    }
  }).catch(()=>{
    loading.close();
    ElMessageBox.confirm(
        '该商品信息查询存在问题',
        '提示',
        {
          type: 'danger',
          showCancelButton: false
        }
    ).then(()=>{
      toBack();
    })
  })
}
function toBack(){
  const obj = { path: "/gasManage/stockManage/goodInfo" };
  proxy.$tab.closeOpenPage(obj);
}
</script>
<style scoped lang="scss">
@import "@/assets/styles/public.scss";
.app-container{
  width: 100%;
  background: $formBgset4;
  min-height: calc(100vh - $navBarHeight);
  .pageContent {
    width: 100%;
    min-width: 1200px;
    min-height: $pageMinHeight;
    border-radius: 6px;
    box-sizing: border-box;
    padding-top: 20px;
    .goodInfoBox{
      width: calc(100% - 40px);
      margin: 0 auto;
    }
    .pageContentTop{
      width: calc(100% - 40px);
      height: 40px;
      margin: 20px auto 0 auto;
      .itemBox{
        width: calc((100% - 10px) / 3);
        height: 100%;
        position: relative;
        background: #F7F8FA;
        margin-right: 2px;
        font-weight: 500;
        font-size: 16px;
        color: #4E5969;
        line-height: 40px;
        box-sizing: border-box;
        padding-left: 60px;
        cursor: pointer;
        .sanBox{
          width: 28px;
          height: 28px;
          background: #F7F8FA;
          transform-origin: center center;
          transform: rotate(45deg);
          position: absolute;
          top: 6px;
          right: -14px;
          z-index: 1;
        }
        .whiteSanBox{
          width: 28px;
          height: 28px;
          background: #FFFFFF;
          transform-origin: center center;
          transform: rotate(45deg);
          position: absolute;
          top: 6px;
          left: -14px;
        }
        &:first-child{
          padding-left: 16px;
        }
        &.active{
          background: var(--el-color-primary);
          color: #FFFFFF;
          .sanBox{
            background: var(--el-color-primary);
          }
        }
      }
    }
    .formBox{
      width: 100%;
      padding: 20px;
      :deep(.el-input){
        .el-input__wrapper{
          background-color: $formBgSet;
          box-shadow: none;
        }
      }
      :deep(.el-textarea){
        .el-textarea__inner{
          background-color: $formBgSet;
          box-shadow: none;
        }
      }
      .normalBox{
        width: 100%;
        border: 1px solid $borderColor;
        .titleBox{
          width: 100%;
          height: 44px;
          background: $formBgset3;
          padding-left: 8px;
          box-sizing: border-box;
          .line{
            width: 4px;
            height: 16px;
            background: $formBgset2;
            margin-right: 8px;
          }
          .title{
            height: 16px;
            line-height: 16px;
            font-weight: 500;
            font-size: 16px;
            color: #1D2129;
          }
        }
        .contentBox{
          width: 100%;
          padding: 24px 0;
          .inputBox{
            width: 360px;
            height: 32px;
          }
          .textareaBox{
            width: 360px;
          }
          .selectOptionBox{
            width: 360px;
          }
          .valueBox{
            width: 360px;
            height: 32px;
            background-color: $formBgSet;
            padding: 0 10px;
            color: var(--el-text-color-regular);
            cursor: pointer;
            .value{
              flex: 1;
            }
          }
          .imgBox{
            min-width: 360px;
            background: $formBgSet;
            border-radius: 4px;
            padding: 12px;
            .notice{
              height: 20px;
              font-weight: 400;
              font-size: 12px;
              color: #86909C;
              line-height: 20px;
              margin-top: 12px;
            }
          }
        }
        .line{
          width: 100%;
          height: 3px;
          background-color: $formBgset4;
        }
        .dataManageBottom{
          width: 100%;
          height: 72px;
        }
      }
    }
  }
}
</style>